package io.gitee.pkmer.ddd.shared.dispatch;

import io.gitee.pkmer.ddd.shared.command.Command;
import io.gitee.pkmer.ddd.shared.command.CommandHandler;
import io.gitee.pkmer.designpattern.strategy.StrategyChoose;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 使用策略模式统一处理{@link Command}
 * 子类使用
 * // @Service
 * // public class CourseCmdService extends CmdService {}
 *
 * @author 胖卡
 * @version 1.0.0
 * @date 2024/7/14
 */

@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class CmdDispatcher extends StrategyChoose<
        Command,
        Class<? extends Command>,
        CommandHandler<Command,Object>>{

    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    public CmdDispatcher(){
        super();
        log.info("DDD 命令分发器初始化中");
    }

    /**
     * 统一处理处理Command，有返回值
     * @param command 命令
     * @return R
     * @param <R> 返回结果
     */
    public <R> R dispatch(Command command){
        log.info("执行：{}",command.getClass().getSimpleName());
        CommandHandler<Command, Object> handler = super.choose(command.getClass());
        return (R)handler.execute(command);
    }
}
